package com.atguigu.u_reentrankReadWriteLock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/*十次读 十次写
* 读的过程可以共享
* 写的过程不可以共享*/

class ReadSndWrite{
    Map<String,String> map = new HashMap<>();

    ReentrantLock lock = new ReentrantLock();
    ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    // 读
    public void read(String key){
        readWriteLock.readLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"开始读..");
            String s = map.get(key);
            System.out.println(Thread.currentThread().getName()+"结束读.."+s);
        }finally {
            readWriteLock.readLock().unlock();
        }
    }

    // 写
    public void write(String key,String value){
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"开始写..");
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"结束写..");
        }finally {
            readWriteLock.writeLock().unlock();
        }
    }
}

public class MyReentrantWriteReadLock {
    public static void main(String[] args) {
        ReadSndWrite readSndWrite = new ReadSndWrite();

        // 写
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(()->{
               readSndWrite.write(finalI +"", finalI +"");
            }, String.valueOf(i)).start();

        }
        // 读
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(()->{
                readSndWrite.read(finalI+"");
            }, String.valueOf(i)).start();
        }
    }
}
